import { PdfJs, SpecialZoomLevel } from "../../core";

import BookmarkList from "./BookmarkList";
import RightArrowIcon from "./RightArrowIcon";
import { FC, useRef } from "react";

interface BookmarkItemProps {
  bookmark: PdfJs.Outline;
  depth: number;
  doc: PdfJs.PdfDocument;
  onClick(dest: PdfJs.OutlineDestinationType): void;
  onJumpToDest(
    pageIndex: number,
    bottomOffset: number,
    scaleTo: number | SpecialZoomLevel
  ): void;
}

const BookmarkItem: FC<BookmarkItemProps> = ({
  bookmark,
  depth,
  doc,
  onClick,
  onJumpToDest,
}) => {
  const toggleRef = useRef<HTMLSpanElement>(null);
  const subItemRef = useRef<HTMLDivElement>(null);
  const subItemsDisplayed = useRef(true);

  const hasSubItems = bookmark.items && bookmark.items.length > 0;

  const toggleSubItems = (): void => {
    subItemsDisplayed.current = !subItemsDisplayed.current;
    const subItemsEle = subItemRef.current;
    const toggleEle = toggleRef.current;
    if (!subItemsEle || !toggleEle) {
      return;
    }
    subItemsEle.style.display = subItemsDisplayed.current ? "block" : "none";
    toggleEle.classList.toggle("rpv-bookmark__toggle--expanded");
  };

  const clickBookmark = (): void => {
    if (hasSubItems && bookmark.dest) {
      onClick(bookmark.dest);
    }
  };
  const clickItem = (): void => {
    if (!hasSubItems && bookmark.dest) {
      onClick(bookmark.dest);
    }
  };

  return (
    <>
      <div
        className="rpv-bookmark__item"
        style={{
          paddingLeft: `${depth * 20 + 4}px`,
        }}
        onClick={clickItem}
      >
        {hasSubItems && (
          <span
            ref={toggleRef}
            className="rpv-bookmark__toggle"
            onClick={toggleSubItems}
          >
            <RightArrowIcon />
          </span>
        )}
        {bookmark.url ? (
          <a
            className="rpv-bookmark__title"
            href={bookmark.url}
            rel="noopener noreferrer nofollow"
            target={bookmark.newWindow ? "_blank" : ""}
          >
            {bookmark.title}
          </a>
        ) : (
          <div className="rpv-bookmark__title" onClick={clickBookmark}>
            {bookmark.title}
          </div>
        )}
      </div>
      {hasSubItems && (
        <div ref={subItemRef}>
          <BookmarkList
            bookmarks={bookmark.items}
            depth={depth + 1}
            doc={doc}
            onJumpToDest={onJumpToDest}
          />
        </div>
      )}
    </>
  );
};

export default BookmarkItem;
